<?php
// +----------------------------------------------------------------------
// | 用户模型
// +----------------------------------------------------------------------
// | 深圳市君鉴测试仪器租赁有限公司
// +----------------------------------------------------------------------
// | Author: 卓战友 125323228@qq.com
// +----------------------------------------------------------------------

namespace Chrent\Model;
use Think\Model;

class UsersModel extends Model {

    public function lists($status = 1, $order = 'uid DESC', $field = true){
        $map = array('status' => $status);
        return $this->field($field)->where($map)->order($order)->select();
    }

    /**
     * 登录指定用户
     * @param  varchar $username 用户名
	 * @param  varchar $password 用户密码
     * @return boolean      ture-登录成功，false-登录失败
	 * @Author: 卓战友 125323228@qq.com
     */
    public function login($username, $password){
        /* 检测是否在当前应用注册 */
		$map['user_name'] = $username;
		$user = $this->where($map)->find();
		if(is_array($user) && $user['status']){
			/* 验证用户密码 */
			if(chrent_md5($password) !== $user['password']){
				$this->error = '密码错误！'; 
				return false;
			}
		} else {
            $this->error = '用户不存在或已被禁用！'; 
            return false;
		}

        //记录行为
        //action_log('user_login', 'user', $uid, $uid);

        /* 登录用户 */
        $this->autoLogin($user);
        return true;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('user', null);
        session('user_auth_sign', null);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 更新登录信息 */
        $data = array(
            'uid'             => $user['uid'],
            'visit_count'     => array('exp', '`visit_count`+1'),
            'last_login_time' => NOW_TIME,
            'last_login_ip'   => get_client_ip(1),
        );
        $this->save($data);

        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $user['uid'],
            'user_name'       => $user['user_name'],
			'real_name'       => $user['real_name'],
			'mobile'       => $user['mobile'],
            'last_login_time' => $user['last_login_time'],
        );

        session('user', $auth);
        session('user_auth_sign', data_auth_sign($auth));

    }
}